/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package exatrez.stripes.action;

import able.stripes.JSP;
import com.google.inject.Inject;
import exatrez.dao.PenggunaDAO;
import exatrez.dao.PersonalTaskDAO;
import exatrez.manager.ObservationManager;
import exatrez.manager.TaskManager;
import exatrez.model.Document;
import exatrez.model.Gallery;
import exatrez.model.Observation;
import exatrez.model.ObservationSummary;
import exatrez.model.ObservationTask;
import exatrez.model.PersonalTask;
import exatrez.model.TaskSummary;
import exatrez.model.User;
import exatrez.stripes.BaseActionBean;
import exatrez.stripes.Configuration;
import exatrez.stripes.util.ReportUtil;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ErrorResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author fikri
 */
@UrlBinding("/report")
public class ReportAction extends BaseActionBean{
    
    @Inject
    private ObservationManager observationManager;    
    
    private List<Observation> list;
    
    @Inject
    private Configuration conf;
    
    @Inject
    private ReportUtil reportUtil;
    
    private Observation observation;
    @Inject
    private PenggunaDAO userDAO;
    
    private static Logger LOG = LoggerFactory.getLogger(ReportAction.class);
    
    // for personal task report
    @Inject
    private PersonalTaskDAO personalTaskDAO;
    @Inject
    private TaskManager taskManager;
    
    @DefaultHandler
    public Resolution showForm() {
        return new JSP("report/list_report.jsp");
    }
    
    public Resolution search() {
        list = observationManager.findAll(observation);
        return new JSP("report/list_report.jsp");
    }
    
    public Resolution genReport() {
        SimpleDateFormat d = new SimpleDateFormat("dd MMM yyyy");
        Observation obs = null;
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();        
        Map<String,Object> parameter = new HashMap<String,Object>();
        
        String id = getContext().getRequest().getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            obs = observationManager.getObservation(id);
            if (obs != null) {
                parameter.put("vessel_name", obs.getVessel().getVesselName());
                parameter.put("location", obs.getLocation());
                parameter.put("date_inspection", d.format(obs.getDateOfInspection()));
                parameter.put("nameMaster", obs.getNameMaster());
                parameter.put("nameChief", obs.getNameChief());
                parameter.put("nameOfficer", obs.getNameOfficer());
                parameter.put("nameEngineer", obs.getNameEngineer());
                List<ObservationSummary> summary = obs.getSummaryList();                
                int count = 1;
                for (ObservationSummary sum : summary) {
                    parameter.put("summary"+count, sum.getSummary());
                    count++;
                }
                
                List<ObservationTask> tasks = obs.getTaskList();
                count = 1;
                for (ObservationTask task : tasks) {
                    Map<String,String> map = new HashMap<String,String>();
                    map.put("no", String.valueOf(count));
                    map.put("finding", task.getDetail());
                    if (task.getSeverity().getSeverityCodeId() == 1) {
                        map.put("c_low", "x");
                    } else if (task.getSeverity().getSeverityCodeId() == 2) {
                        map.put("c_medium", "x");
                    } else {
                        map.put("c_high", "x");
                    }
                    map.put("info", task.getInfo());
                    map.put("photo", "");
                    list.add(map);
                    count++;
                }
                parameter.put("p_list", list);
                
            } else {                
                return new ErrorResolution(404, "ID NOT FOUND!!");
            }
        } else {
            return new ErrorResolution(404, "ID NOT FOUND!!");
        }      
        
        
        final byte[] bytes = reportUtil.generateReportJasper("main_report.jasper", parameter);
        
        return new StreamingResolution("application/pdf") {

            @Override
            public void stream(HttpServletResponse response) throws Exception {
                response.setHeader("Cache-Control", "no-cache");
                response.setHeader("Pragma", "no-cache");
                response.setDateHeader("Expires", 0);
                response.setHeader("Content-disposition", "inline; filename=test.pdf");
                ServletOutputStream out = response.getOutputStream();
                out.write(bytes);
                out.flush();
                out.close();

            }
        };
    }
    
    
    public Resolution genReportByIText () {
        
        SimpleDateFormat d = new SimpleDateFormat("dd MMMM yyyy");
        SimpleDateFormat year = new SimpleDateFormat("yyyy");
        SimpleDateFormat fulltime = new SimpleDateFormat("dd-MMMM-yyyy hh:mm:ss a");
        Date now = new Date();
        Observation obs = null;
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();        
        Map<String,Object> parameter = new HashMap<String,Object>();
        User user = getContext().getCurrentUser();
        LOG.debug("currentUser :"+user.getUserId()+", currentYear :"+year.format(now));
        
        String id = getContext().getRequest().getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            obs = observationManager.getObservation(id);
            String path = conf.getProperty("document.path");
            String reportPath = conf.getProperty("report.path");
            String galleryPath = conf.getProperty("gallery.path");
            if (obs != null) {
                parameter.put("date_now", fulltime.format(now));
                parameter.put("report_path", reportPath);
                parameter.put("gallery_path", galleryPath);
                parameter.put("vessel_name", obs.getVessel().getVesselName().toUpperCase());
                parameter.put("location", obs.getLocation());
                parameter.put("date_inspection", d.format(obs.getDateOfInspection()).toUpperCase());
                parameter.put("nameMaster", obs.getNameMaster());
                parameter.put("nameChief", obs.getNameChief());
                parameter.put("nameOfficer", obs.getNameOfficer());
                parameter.put("nameEngineer", obs.getNameEngineer());
                List<ObservationSummary> summary = obs.getSummaryList();                
                int count = 1;
                for (ObservationSummary sum : summary) {
                    parameter.put("summary"+count, sum.getSummary());
                    if(sum.getInfoAudit() == null)
                        parameter.put("ma"+count, "");
                    else
                        parameter.put("ma"+count, sum.getInfoAudit().getCreateId().getUserId());
                    
                    count++;
                }
                
                List<Gallery> galleries = obs.getVessel().getGalleryList();
                List<Gallery> galleriesByUser = new ArrayList<Gallery>();
                for (Gallery gallery : galleries) {
                    User ug = userDAO.findById(gallery.getUploadedBy());
                    if(ug.getRoles().get(0).getUserGroupId().equals(user.getRoles().get(0).getUserGroupId()) && year.format(now).equals(gallery.getYear()))  //only current user upload photo gallery on current year only
                        galleriesByUser.add(gallery);
                }
                parameter.put("p_gallery", galleriesByUser);
                
                List<ObservationTask> tasks = obs.getTaskList();
                
                count = 1;
                for (ObservationTask task : tasks) {
                    List<String> documents = new ArrayList<String>();
                    Map<String,Object> map = new HashMap<String,Object>();
//                    map.put("no", String.valueOf(count));
                    map.put("obsId", task.getObservationTaskId());
                    map.put("finding", task.getDetail());
                    map.put("severity", task.getSeverity().getSeverityName());
                    map.put("info", task.getInfo());
                    if (task.getFolder() != null) {
                        List<Document> docu = task.getFolder().getDocuments();
                        for (Document dd : docu) {
                            if(dd.getContentType() != null){
                                LOG.debug("dd.docID :"+dd.getDocumentId()+"substr :"+dd.getContentType().substring(0, 5));
                                if(dd.getContentType().substring(0, 5).equals("image"))
                                    documents.add(path + dd.getDocumentPath());
                                else
                                    LOG.error("dd.docID :"+dd.getDocumentId()+", mime type : "+dd.getContentType()+" is not image.");
                            }
                        }
                    }
                    
                    map.put("photo", documents);
                    list.add(map);
                    count++;
                }
                parameter.put("p_list", list);
                parameter.put("date", d.format(new Date()));
                
            } else {                
                return new ErrorResolution(404, "ID NOT FOUND!!");
            }
        } else {
            return new ErrorResolution(404, "ID NOT FOUND!!");
        }          
        
         final byte[] b = reportUtil.generateReportIText( "summary_report.st", parameter );
         
         return new StreamingResolution("application/pdf") {

            @Override
            public void stream(HttpServletResponse response) throws Exception {
                Date now = new Date();
                SimpleDateFormat fulldatetime = new SimpleDateFormat("ddMMMMyyyyhhmmssa");
                response.setHeader("Cache-Control", "no-cache");
                response.setHeader("Pragma", "no-cache");
                response.setDateHeader("Expires", 0);
                response.setHeader("Content-disposition", "inline; filename=MATS-Observation-"+fulldatetime.format(now)+".pdf");
                ServletOutputStream out = response.getOutputStream();
                out.write(b, 0, b.length);
                out.flush();
                out.close();

            }
        };
    }    
    
    
    public Resolution genReportActionPlanByIText () {
        
        SimpleDateFormat d = new SimpleDateFormat("dd MMM yyyy hh:mm:ss");
        SimpleDateFormat dtitle = new SimpleDateFormat("dd MMMM yyyy");
        SimpleDateFormat fulltime = new SimpleDateFormat("dd-MMMM-yyyy hh:mm:ss a");
        Date now = new Date();
        Observation obs = null;
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();        
        Map<String,Object> parameter = new HashMap<String,Object>();
        
        String id = getContext().getRequest().getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            obs = observationManager.getObservation(id);
            String reportPath = conf.getProperty("report.path");
            String documentPath = conf.getProperty("document.path");
            
            if (obs != null) {
                parameter.put("date_now", fulltime.format(now));
                parameter.put("report_path", reportPath);
                parameter.put("document_path", documentPath);
                parameter.put("vessel_name", obs.getVessel().getVesselName().toUpperCase());
                parameter.put("location", obs.getLocation());
                parameter.put("date_inspection", dtitle.format(obs.getDateOfInspection()).toUpperCase());
                parameter.put("nameMaster", obs.getNameMaster());
                parameter.put("nameChief", obs.getNameChief());
                parameter.put("nameOfficer", obs.getNameOfficer());
                parameter.put("nameEngineer", obs.getNameEngineer());
                List<ObservationTask> tasks = obs.getTaskList();
                parameter.put("p_list", tasks);                
                
            } else {                
                return new ErrorResolution(404, "ID NOT FOUND!!");
            }
        } else {
            return new ErrorResolution(404, "ID NOT FOUND!!");
        }          
        
         final byte[] b = reportUtil.generateReportIText( "action_plan_report.st", parameter );
         
         return new StreamingResolution("application/pdf") {

            @Override
            public void stream(HttpServletResponse response) throws Exception {
                Date now = new Date();
                SimpleDateFormat fulldatetime = new SimpleDateFormat("ddMMMMyyyyhhmmssa");
                response.setHeader("Cache-Control", "no-cache");
                response.setHeader("Pragma", "no-cache");
                response.setDateHeader("Expires", 0);
                response.setHeader("Content-disposition", "inline; filename=MATS-ActionPlan-"+fulldatetime.format(now)+".pdf");
                ServletOutputStream out = response.getOutputStream();
                out.write(b, 0, b.length);
                out.flush();
                out.close();

            }
        };
    }
    
    // for personal task report
    public Resolution genReportPersonalTaskByIText () {
        
        SimpleDateFormat dtitle = new SimpleDateFormat("dd MMMM yyyy");
        SimpleDateFormat fulltime = new SimpleDateFormat("dd-MMMM-yyyy hh:mm:ss a");
        Date now = new Date();
        PersonalTask pt = null;
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();        
        Map<String,Object> parameter = new HashMap<String,Object>();
        
        String id = getContext().getRequest().getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            pt = personalTaskDAO.findById(Integer.parseInt(id));
            String reportPath = conf.getProperty("report.path");
            String documentPath = conf.getProperty("document.path");
            User user = getContext().getCurrentUser();
            String department = user.getDepartment().getDepartmentName().toUpperCase();
            
            if (pt != null) {
                parameter.put("department", department);
                parameter.put("date_now", fulltime.format(now));
                parameter.put("report_path", reportPath);
                parameter.put("document_path", documentPath);
                parameter.put("subject", pt.getSubject().toUpperCase());
                parameter.put("date_sent", dtitle.format(pt.getInfoAudit().getCreateDate()));
                parameter.put("priority", pt.getPriorityCode().getPriorityName());
                parameter.put("status", pt.getStatusRemarks());
                List<TaskSummary> ptasks = taskManager.findSummaryTask(id);
                parameter.put("pt_list", ptasks);
                
            } else {                
                return new ErrorResolution(404, "ID NOT FOUND!!");
            }
        } else {
            return new ErrorResolution(404, "ID NOT FOUND!!");
        }          
        
         final byte[] b = reportUtil.generateReportIText( "personal_task_report.st", parameter );
         
         return new StreamingResolution("application/pdf") {

            @Override
            public void stream(HttpServletResponse response) throws Exception {
                Date now = new Date();
                SimpleDateFormat fulldatetime = new SimpleDateFormat("ddMMMMyyyyhhmmssa");
                response.setHeader("Cache-Control", "no-cache");
                response.setHeader("Pragma", "no-cache");
                response.setDateHeader("Expires", 0);
                response.setHeader("Content-disposition", "inline; filename=MATS-PT-"+fulldatetime.format(now)+".pdf");
                ServletOutputStream out = response.getOutputStream();
                out.write(b, 0, b.length);
                out.flush();
                out.close();

            }
        };
    }
    

    public List<Observation> getList() {
        return list;
    }

    public void setList(List<Observation> list) {
        this.list = list;
    }

    public Observation getObservation() {
        return observation;
    }

    public void setObservation(Observation observation) {
        this.observation = observation;
    }

    
}
